<template>
  <div class="package-edit-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>入库清单填写</span>
          <el-button type="primary" @click="handleSubmit">保存操作</el-button>
        </div>
      </template>

      <el-form ref="operationFormRef" :model="formData" :rules="rules" label-position="top">
        <el-form-item label="选择仓库" prop="warehouseId">
          <el-select v-model="formData.warehouseId" placeholder="请选择仓库">
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id || ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库清单标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入库清单标题"></el-input>
        </el-form-item>
        <el-form-item label="入库清单操作类型" prop="operation">
          <el-select v-model="formData.operation" placeholder="请选择">
            <el-option
              v-for="item in InInventoryOperation"
              :key="item"
              :label="InventoryOperation_LABEL[item]"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库清单描述" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入入库清单描述"
          ></el-input>
        </el-form-item>

        <EditTable ref="editTableRef" title="入库材料清单" @add-window="showMaterialWindow()" />
      </el-form>
    </el-card>

    <!-- 材料弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      @close="closeMaterialWindow"
    >
      <MaterialSelector ref="materialRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseMaterialDone">确 定</el-button>
          <el-button @click="closeMaterialWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import EditTable from "./edit-table.vue";
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";
import InventoryAPI, { InventoryForm } from "@/api/business/warehouse/inventory.api";
import WarehouseAPI, { WarehousePageVO } from "@/api/business/warehouse/warehouse.api";
import {
  InventoryOperation_LABEL,
  InInventoryOperation,
} from "@/api/business/warehouse/warehouseEnum";
import { MaterialChooseVO, MaterialPageVO } from "@/api/business/material/material.api";

defineOptions({
  name: "WarehouseOperation",
  inheritAttrs: false,
});

const route = useRoute();
const materialRef = ref();
const operationFormRef = ref();
const editTableRef = ref();

const warehouseId = ref("");
const formData = reactive<InventoryForm>({
  items: [],
  operation: InInventoryOperation.IN,
});
const warehouseList = reactive<WarehousePageVO[]>([]);

const dialog = reactive({
  title: "材料列表",
  visible: false,
});

onMounted(() => {
  loadWarehouses();
});

onActivated(() => {
  if (route.query.warehouseId == warehouseId.value) return;
  clear();
  warehouseId.value = route.query.warehouseId as string;
  if (warehouseId.value && warehouseId.value !== "0") {
    formData.warehouseId = warehouseId.value;
  }
});

const chooseMaterialDone = () => {
  try {
    let curList: MaterialPageVO[] = materialRef.value.getChecked();
    if (!curList || curList.length === 0) return;
    editTableRef.value.addMaterial(curList.map((item) => ({ ...item, num: 1 })));
  } catch (error) {
    ElMessage.error("添加失败");
    console.error("添加失败", error);
  } finally {
    dialog.visible = false;
  }
};

function showMaterialWindow() {
  dialog.visible = true;
  nextTick(() => {
    materialRef.value.handleQuery();
  });
}

function closeMaterialWindow() {
  dialog.visible = false;
}

const handleSubmit = async () => {
  operationFormRef.value.validate((valid: any) => {
    const materials: MaterialChooseVO[] = editTableRef.value.getData();
    formData.items = materials.map(({ id, code, num, type }) => ({
      materialId: id,
      sku: code,
      quantity: num,
      type: type,
    }));
    if (valid) {
      InventoryAPI.create(formData)
        .then(() => {
          ElMessage.success("入库成功");
        })
        .finally(() => {
          clear();
        });
    }
  });
};
const clear = () => {
  formData.items = [];
  editTableRef.value.clearData();
  operationFormRef.value.resetFields();
};

const rules = reactive({
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "blur" }],
  title: [{ required: true, message: "请输入库存操作标题", trigger: "blur" }],
  operation: [{ required: true, message: "请选择库存操作类型", trigger: "blur" }],
});

const loadWarehouses = () => {
  WarehouseAPI.loadAll().then((data) => {
    if (data.length > 0) {
      warehouseList.push(...data);
    }
  });
};
</script>

<style scoped>
.package-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
